package com.ys.service.storage.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.dto.AddDto;
import com.ys.entity.base.CheckByGrid;
import com.ys.entity.storage.TccPreAllocatePublish;
import com.ys.entity.storage.TccPreAllocatePublishItem;
import com.ys.entity.sys.*;
import com.ys.mapper.storage.StorageMapper;
import com.ys.mapper.storage.TccPreAllocatePublishItemMapper;
import com.ys.mapper.storage.TccPreAllocatePublishMapper;
import com.ys.service.storage.TccPreAllocatePublishService;
import com.ys.util.CheckUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 预约调拨发布单
 */
@Service("tccPreAllocatePublishService")
public class TccPreAllocatePublishServiceImpl implements TccPreAllocatePublishService {
	private static final Logger logger = LoggerFactory.getLogger(TccPreAllocatePublishServiceImpl.class);

	@Autowired
	private TccPreAllocatePublishMapper tccPreAllocatePublishMapper;

	@Autowired
	private TccPreAllocatePublishItemMapper tccPreAllocatePublishItemMapper;


	@Autowired
	private CheckUtil checkUtil;

	@Autowired
	private StorageMapper storageMapper;


	private final Long GRID = 67L;

	/**
	 * 新增
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R add(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("新增传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TccPreAllocatePublish entity = JSON.parseObject(JSON.toJSONString(params), TccPreAllocatePublish.class);


		String loginUserId = ShiroUtils.getUserId();
		TsUserChange tsUserChange = new TsUserChange().setUserId(loginUserId).setStatus(1).queryFirst();
		entity.setCreateChangeId(tsUserChange.getId());
		entity.setStatus(1);//状态
		entity.setAllocateQuantity(BigDecimal.ZERO);//已调数量 0
		//保存列表信息
		R saveItemRes = saveItem(params,entity);
		if(saveItemRes.getCode()==1){
			return saveItemRes;
		}

		//新增
		tccPreAllocatePublishMapper.insert(entity);

		//return R.ok(EditDto.closeAndReload());
		return R.ok(AddDto.gotoEdit("/web/storage/tccPreAllocatePublish/toEdit?bid=" + entity.getBid()));
	}


	/**
	 * 修改
	 */
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R update(Map<String, Object> params, Long menuId) throws Exception{
		logger.info("修改传参:"+params);
		//参数验证
		String errorBack = checkParams(params, menuId);
		if(errorBack!=null && !"".equals(errorBack)){
			return R.error(errorBack);
		}
		TccPreAllocatePublish entity = JSON.parseObject(JSON.toJSONString(params), TccPreAllocatePublish.class);

		//保存列表信息
		R saveItemRes = saveItem(params,entity);
		if(saveItemRes.getCode()==1){
			return saveItemRes;
		}
		tccPreAllocatePublishMapper.update(entity);
		return R.ok();
	}


	//保存列表信息
	public R saveItem(Map<String, Object> params,TccPreAllocatePublish entity) throws Exception{
		//保存列表信息
		List<Map<String, Object>> subDataList = new ArrayList<>();
		if(params.get("subData")!=null){
			JSONArray subData = JSON.parseArray(params.get("subData").toString());
			CheckByGrid checkByGrid = checkParamsByGrid(subData,GRID,params);
			if(checkUtil.isNotNullByObject(checkByGrid.getErrMsg())){
				return R.error(checkByGrid.getErrMsg());
			}
			subDataList = checkByGrid.getSubDataList();
			if(subDataList!=null && subDataList.size()>0){
				List<TccPreAllocatePublishItem> oldList = new TccPreAllocatePublishItem()
						.setPbid(entity.getBid())
						.queryList();

				saveItemNoDelAll(oldList,subDataList,entity);
			}else {
				addItemByNone(entity);
			}
		}else {
			addItemByNone(entity);
		}


		return R.ok();
	}

	//子列表为空时的处理
	public void addItemByNone(TccPreAllocatePublish entity) throws Exception{
		//删除可能存在的列表信息
		storageMapper.delTccPreAllocatePublishItemByBid(entity.getBid());
		TccPreAllocatePublishItem itemInfo = new TccPreAllocatePublishItem();
		itemInfo.setPbid(entity.getBid());
		itemInfo.setFromIsShow(0);
		itemInfo.setStatus(1);
		itemInfo.setPublishAmountByReality(entity.getPublishAmount());
		tccPreAllocatePublishItemMapper.insert(itemInfo);
	}


	//非全量删除再新增，与原数据对比后进行处理
	public void saveItemNoDelAll(List<TccPreAllocatePublishItem> oldList,List<Map<String, Object>> newList,TccPreAllocatePublish entity) throws Exception{
		String bid = entity.getBid();
		if(oldList!=null && oldList.size()>0){
			for(TccPreAllocatePublishItem oldItem:oldList){
				boolean isDel = true;
				for(Map<String, Object> newItem:newList){
					TccPreAllocatePublishItem itemInfo = JSON.parseObject(JSON.toJSONString(newItem), TccPreAllocatePublishItem.class);
					if(checkUtil.isNotNullByObject(itemInfo.getId())){
						if(itemInfo.getId().equals(oldItem.getId())){
							isDel = false;
						}
					}
				}
				if(isDel){
					tccPreAllocatePublishItemMapper.deleteTrue(oldItem.getId());
				}
			}

			for (Map<String, Object> item:newList) {
				TccPreAllocatePublishItem itemInfo = JSON.parseObject(JSON.toJSONString(item), TccPreAllocatePublishItem.class);
				//itemInfo.setStatus(1);
				itemInfo.setPbid(bid);
				if(itemInfo.getPublishAmountBySon() == null || itemInfo.getPublishAmountBySon().compareTo(BigDecimal.ZERO)==0){
					itemInfo.setPublishAmountByReality(entity.getPublishAmount());
				}else {
					itemInfo.setPublishAmountByReality(itemInfo.getPublishAmountBySon());
				}
				itemInfo.setFromIsShow(1);
				if(checkUtil.isNotNullByObject(itemInfo.getId())){
					//修改
					tccPreAllocatePublishItemMapper.update(itemInfo);
				}else {
					//新增
					tccPreAllocatePublishItemMapper.insert(itemInfo);
				}
			}
		}else {
			for (Map<String, Object> item:newList) {
				TccPreAllocatePublishItem itemInfo = JSON.parseObject(JSON.toJSONString(item), TccPreAllocatePublishItem.class);
				//itemInfo.setStatus(1);
				itemInfo.setPbid(bid);
				if(itemInfo.getPublishAmountBySon() == null || itemInfo.getPublishAmountBySon().compareTo(BigDecimal.ZERO)==0){
					itemInfo.setPublishAmountByReality(entity.getPublishAmount());
				}else {
					itemInfo.setPublishAmountByReality(itemInfo.getPublishAmountBySon());
				}
				itemInfo.setFromIsShow(1);
				//新增
				tccPreAllocatePublishItemMapper.insert(itemInfo);
			}
		}
	}



	//删除
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R del(Long id) throws Exception{
		if (id == null) {
			return R.error("ID不能为空");
		}
		TccPreAllocatePublish entity = new TccPreAllocatePublish().setId(id).queryFirst();
		//删除
		tccPreAllocatePublishMapper.deleteTrue(id);
		//删除列表信息
		storageMapper.delTccPreAllocatePublishItemByBid(entity.getBid());
		return R.ok();
	}



	//停用
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public R stop(Long id) throws Exception{
		if (id == null) {
			return R.error("ID不能为空");
		}
		TccPreAllocatePublishItem item = new TccPreAllocatePublishItem().setId(id).setStatus(0);
		//修改状态
		tccPreAllocatePublishItemMapper.update(item);
		return R.ok();
	}


	/**
	 * 参数验证
	 */
	public String checkParams(Map<String, Object> params, Long menuId) throws Exception {
		//获取pc字段数据
		List<YsCol> listField = new YsCol()
				.where("A.MenuId = "+menuId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		//验证必填字段的非空；其他字段的长度限制、类型
		String backMsg = checkUtil.checkTableColLengthAndDataType("TCC_PreAllocatePublish",listField,params,ysColItem->ysColItem.getFormEditRequired()!=null && ysColItem.getFormEditRequired() == 1);
		return backMsg;
	}


	/**
	 * 子表参数验证
	 */
	public CheckByGrid checkParamsByGrid(JSONArray subDataArray, Long gridId,Map<String, Object> params) throws Exception {
		CheckByGrid checkByGrid = new CheckByGrid();
		//获取pc字段数据
		List<YsGridCol> listField = new YsGridCol()
				.setGridId(gridId)
				.setOrderby("A.SortNo ASC")
				.queryList();
		String backMsg = "";
		List<Map<String, Object>> subDataList = new ArrayList<>();

		if(subDataArray!=null && subDataArray.size()>0){
			for (int i = 0; i < subDataArray.size(); i++) {
				JSONObject jsonObject = subDataArray.getJSONObject(i);
				Map<String, Object> paramsNewByRecord = new HashMap<>();
				for (String key : jsonObject.keySet()) {
					paramsNewByRecord.put(key, jsonObject.get(key));
				}
				subDataList.add(paramsNewByRecord);
			}
			//验证
			for(int i = 0;i<subDataList.size();i++){
				String backMsgByRow = "";
				Map<String, Object> subData = subDataList.get(i);
				//验证必填字段的非空；其他字段的长度限制、类型
				backMsgByRow += checkUtil.checkTableColLengthAndDataTypeByGrid(
						"TCC_PreAllocatePublishItem",
						listField,
						subData,
						ysColItem->
								ysColItem.getCode().equals("publishVgsbm")
				);

				if(checkUtil.isNotNullByObject(backMsgByRow)){
					backMsg += "列表第" + (i+1) + "行，" + backMsgByRow;
				}
			}
		}
		checkByGrid.setErrMsg(backMsg);
		checkByGrid.setSubDataList(subDataList);

		return checkByGrid;
	}


	//根据主表bid获取子表信息
	@Override
	@Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
	public List<Map<String,Object>> getItemListByBid(String bid) throws Exception {
		//获取子表信息
		List<Map<String,Object>> itemList = new TccPreAllocatePublishItem()

				.addLeftJoin("THR_OperateCompanyApply B ON B.Vgsbm = A.PublishVgsbm")//运营公司管理表
				.addField("B.Vgsjc AS publishVgsjc")//运营公司简称

				.setPbid(bid)
				.setFromIsShow(1)
				.queryMap();
		return  itemList;
	}




	//获取列表数据
	@Override
	@Transactional
	public Map<String,Object> getExtraParam( String bid) throws Exception{
		Map<String,Object> extraParam = new TccPreAllocatePublish()

				.addLeftJoin("THR_OperateCompanyApply B ON B.Vgsbm = A.Vgsbm")//运营公司管理表
				.addField("B.Vgsjc AS vgsjc")//运营公司简称

				.addLeftJoin("TCC_Warehouse C ON C.Cck = A.WarehouseCode")//仓库表
				.addField("C.Vck AS vck")//仓库名称

				.setBid(bid)
				.queryFirstMap();
		return extraParam;
	}


}
